// 封装权限指令
import type { Directive, DirectiveBinding } from "vue";

export const has: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionList = localStorage.getItem("permissionList");
    const pl = permissionList.split(",");
    if (permissionList === "**" || (pl?.length && pl?.includes(binding.value)) || !binding.value) {
      return true;
    } else {
      el.parentNode.removeChild(el);
    }
  }
};

// 判断一个数组的所有值是否包含在另一个数组内
const isContainsAll = (arr, values) => values.every(val => arr.includes(val));

export const have: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionList = localStorage.getItem("permissionList");
    const pl = permissionList.split(",");
    if (permissionList === "**" || isContainsAll(pl, binding.value) || !binding.value) {
      return true;
    } else {
      el.parentNode.removeChild(el);
    }
  }
};

// 判断一个数组的某个值是否在另一个数组内
const hasElementInArray = (arr, values) => values.some(val => arr.includes(val));

export const or: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionList = localStorage.getItem("permissionList");
    const pl = permissionList.split(",");
    if (permissionList === "**" || hasElementInArray(pl, binding.value) || !binding.value) {
      return true;
    } else {
      el.parentNode.removeChild(el);
    }
  }
};
